﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.ServiceModel.DomainServices.Client;
using C1.Silverlight.DataGrid.Summaries;

namespace DYSales.Views.sell
{
    public partial class main_page : Page
    {
        public main_page()
        {
            InitializeComponent();
            dg_sells.AutoGeneratingColumn += new EventHandler<C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs>(dg_sells_AutoGeneratingColumn);
            dg_sells_detais.AutoGeneratingColumn += new EventHandler<C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs>(dg_sells_detais_AutoGeneratingColumn);
            Loaded += new RoutedEventHandler(main_page_Loaded);
            bt_开单.Click += new RoutedEventHandler(bt_开单_Click);
            dg_sells.LoadedRowPresenter += new EventHandler<C1.Silverlight.DataGrid.DataGridRowEventArgs>(dg_sells_LoadedRowPresenter);
            bt_添加支出.Click += new RoutedEventHandler(bt_添加支出_Click);
            bt_打印小票.Click +=new RoutedEventHandler(bt_打印小票_Click);
        }

        void bt_打印小票_Click(object sender, RoutedEventArgs e)
        {
            if (dg_sells.Selection.SelectedRows.Count == 1)
            {
                dm.getDS().GetSetTable(lo =>
                {
                    if (!lo.HasError)
                    {
                        PrintManager.tbs = new List<TextBlock>();
                        PrintManager.tbcount = 0;
                        var setting = lo.Value;
                        var sell = dg_sells.Selection.SelectedRows.First().DataItem as Web.SellTable;
                        TextBlock tb = PrintManager.CreatePrintTextBlock(setting.s_打印页宽);
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 4, FontWeight = FontWeights.Bold, Text = setting.s_店名 });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 2, Text = setting.s_副标题 });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小, Text = "单号:" + sell.st_流水号 });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new LineBreak());
                        int i = 1;
                        foreach (var item in sell.SellDetails)
                        {
                            if (tb.ActualHeight >= PrintManager.PrintHight)
                            {
                                PrintManager.tbs.Add(tb);
                                tb = PrintManager.CreatePrintTextBlock(setting.s_打印页宽);
                            }
                            tb.Inlines.Add(new Run()
                            {
                                FontSize = setting.s_字体大小,
                                Text = i.ToString() + "." + item.sd_商品名称 + "/" + item.sd_单位
                                + item.sd_单价.ToString("0.##") + "*" + item.sd_数量.ToString("0.##")
                                + "*" + (item.sd_折扣*10).ToString("0.##") + "折 计:" + item.sd_小计.ToString("0.##") 
                            });
                            tb.Inlines.Add(new LineBreak());
                            i++;
                        }
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 2, Text = "消费金额:" + sell.st_消费金额.ToString("0.##") });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 2, Text = "现金支付:" + sell.st_现金支付.ToString("0.##") });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 2, Text = "刷卡支付:" + sell.st_刷卡支付.ToString("0.##") });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 2, Text = "整单折扣:" + (sell.st_整单折扣*10).ToString("0.##") +"折"});
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小 + 2, Text = "实收金额：" + sell.st_实付金额.ToString("0.##") });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小, Text = setting.s_地址 });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小, Text = setting.s_电话 });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小, Text = "操作员：" + WebContext.Current.User.Name });
                        tb.Inlines.Add(new LineBreak());
                        tb.Inlines.Add(new Run() { FontSize = setting.s_字体大小, Text = sell.st_消费时间.ToString() });
                        tb.Inlines.Add(new LineBreak());
                        PrintManager.tbs.Add(tb);

                        PrintManager.GetPrintManager().DoPrint();
                    }
                }, null);
            }
        }

        cwin_expAdd expWin;
        void bt_添加支出_Click(object sender, RoutedEventArgs e)
        {
            dm.getDS().GetST(lo =>
            {
                expWin = new cwin_expAdd();
                expWin.Closed += new EventHandler(expWin_Closed);
                var et = new Web.ExpenditureTable();
                et.exp_备注 = string.Empty;
                et.exp_时间 = lo.Value;
                et.exp_支出金额 = 0;
                expWin.CurrentItem = et;
                expWin.Show();
            }, null);
        }

        void expWin_Closed(object sender, EventArgs e)
        {
            var cwin = sender as cwin_expAdd;
            cwin.Closed -= new EventHandler(expWin_Closed);
            if (cwin.DialogResult.Value)
            {
                dm.getDS().ExpenditureTables.Add(cwin.CurrentItem);
                dm.getDS().SubmitChanges();
            }
            dg_sells.Focus();
        }

        void dg_sells_detais_AutoGeneratingColumn(object sender, C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Property.PropertyType.Equals(typeof(decimal)) || e.Property.PropertyType.Equals(typeof(double)))
            {
                e.Column.Format = "0.##";
            }
            #region 减少列
            string headername = e.Column.Header.ToString();
            switch (headername)
            {
                case "ID":
                case "外键":
                case "进货价":
                    e.Cancel = true;
                    break;

                case "小计":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
            }
            #endregion
        }

        void dg_sells_AutoGeneratingColumn(object sender, C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Property.PropertyType.Equals(typeof(double)))
            {
                e.Column.Format = "0.##";
            }
            else if (e.Property.PropertyType.Equals(typeof(decimal)))
            {
                e.Column.Format = "0.##";
                DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
            }
            if (e.Property.PropertyType.Equals(typeof(DateTime)))
            {
                e.Column.Format = "yyyy/MM/dd HH:mm:ss";
            }
            #region 减少列
            string headername = e.Column.Header.ToString();
            switch (headername)
            {
                case "ID":
                case "外键":
                    e.Cancel = true;
                    break;
            }
            #endregion
        }

        void dg_sells_LoadedRowPresenter(object sender, C1.Silverlight.DataGrid.DataGridRowEventArgs e)
        {
            var helper = new C1.Silverlight.C1MouseHelper(e.Row.Presenter);
            helper.MouseClick += (s, a) =>
            {
                if (dg_sells.Selection.SelectedRows.Count == 1)
                {
                    var d = dg_sells.Selection.SelectedRows.First().DataItem as Web.SellTable;
                    if (d != null)
                    {
                        dg_sells_detais.DataContext = null;
                        dg_sells_detais.DataContext = d.SellDetails;
                    }
                }
            };
        }

        void main_page_Loaded(object sender, RoutedEventArgs e)
        {
            refresh();
        }

        cwin_SellAdd sellWin;
        internal void bt_开单_Click(object sender, RoutedEventArgs e)
        {
            sellWin = new cwin_SellAdd();
            sellWin.Closed += new EventHandler(sellWin_Closed);
            sellWin.Show();
        }

        void sellWin_Closed(object sender, EventArgs e)
        {
            var cwin = sender as cwin_SellAdd;
            cwin.Closed -= new EventHandler(sellWin_Closed);
            if (cwin.DialogResult.Value)
            {
                dg_sells.DataContext = dm.getDS().SellTables;
                if (other.o_自动打印小票)
                {
                    dg_sells.SelectedItem = cwin.nsell;
                    bt_打印小票_Click(null, null);
                }
            }
            dg_sells.Focus();
        }

        void refresh()
        {
            dm.getDS().GetST(lt =>
            {
                dm.getDS().GetSetTable(ls =>
                {
                    var lttime = lt.Value;
                    var lstime = ls.Value.s_营业开始时间;
                    var lstime2 = ls.Value.s_营业结束时间;
                    var start = new DateTime(lttime.Year, lttime.Month, lttime.Day, lstime.Hour, lstime.Minute, lstime.Second);
                    var end = new DateTime(lttime.Year, lttime.Month, lttime.Day, lstime2.Hour, lstime2.Minute, lstime2.Second).AddDays(1);
                    dm.getDS().Load(dm.getDS().GetSellTablesByTimeNameQuery(WebContext.Current.User.Name,
                        start, end), LoadBehavior.RefreshCurrent, lo =>
                    {
                        dg_sells.DataContext = lo.Entities;
                        dg_sells.Focus();
                    }, null);
                }, null);
            }, null);
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

    }
}
